package com.wlyuan.open.domain.api.service;

import com.wlyuan.open.domain.api.OpenApiInfoLog;
import com.wlyuan.open.domain.api.respository.OpenApiInfoLogRepository;
import com.wlyuan.open.domain.api.respository.OpenApiInfoRepository;
import com.wlyuan.open.domain.client.OpenClientId;
import com.wlyuan.open.domain.client.respository.OpenClientApiCacheRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author lijing
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OpenApiInfoLogService {
    private final OpenApiInfoLogRepository openApiInfoLogRepository;
    private final OpenApiInfoRepository openApiInfoRepository;
    private final OpenClientApiCacheRepository openClientApiCacheRepository;

    public void save(OpenClientId clientId, OpenClientId afterClientId) {
        try {
            clientApi(clientId);
            Optional.ofNullable(afterClientId).ifPresent(client -> {
                clientApi(client);
            });
        } catch (Exception e) {
            logger.error("添加访问日志失败：{}", e);
        }
    }

    private void clientApi(OpenClientId clientId) {
        openApiInfoLogRepository.save(new OpenApiInfoLog(clientId.getId(), openApiInfoRepository.getByClientId(clientId)));
        openApiInfoRepository.removeByClient(clientId);
        openClientApiCacheRepository.remove(clientId);
    }
}
